/**
 * 判断是否登录
 * @returns {boolean}
 */
export function isLogin () {
  return !!sessionStorage.getItem('user_info')
}

/**
 * 获取用户名
 * @returns {boolean}
 */
export function getUserName () {
  let user = sessionStorage.getItem('user_info') || '{}'
  user = JSON.parse(user)
  return user.userName
}

/**
 * 获取用户权限节点
 * @returns {*}
 */
export function getUserAccess () {
  return JSON.parse(sessionStorage.getItem('nodes')) || []
}

/**
 * 是否超级管理员
 * @returns {boolean}
 */
function isSuperAdmin () {
  return getUserName() === 'superAdmin'
}

/**
 * 检查路由权限
 * @param route
 * @returns {boolean}
 */
export function checkRouterAccess (route) {
  if (isSuperAdmin()) {
    return true
  }
  const { meta: { access } } = route
  if (access === undefined) {
    return true
  }
  const roles = getUserAccess()
  return checkAccess(access, roles)
}

/**
 * 检查操作权限
 * @param role
 * @returns {boolean}
 */
export function checkActionAccess (role) {
  if (isSuperAdmin()) {
    return true
  }
  if (role === undefined) {
    return true
  }
  const roles = getUserAccess()
  return checkAccess(role, roles)
}

/**
 * 检查权限
 * @param role
 * @param roles
 * @returns {boolean}
 */
export function checkAccess (role, roles = []) {
  // return true
  if (Array.isArray(role)) {
    const expression = role[role.length - 1] || ''
    role.splice(-1, 1)
    if (expression.toUpperCase() === 'OR') {
      console.log(expression)
      return role.some(item => checkAccess(item, roles))
    }
    if (expression.toUpperCase() === 'AND') {
      return role.every(item => checkAccess(item, roles))
    }
  }
  return !!roles.find(item => parseInt(item.id) === parseInt(role))
}
